package com.car.slave.im.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;

import com.car.slave.im.model.user.IMUserMessage;

/**
 * 消息处理广播.
 * @author zhangliucheng
 *
 */
public class IMMessageReceiver extends BroadcastReceiver {
	
	public enum ExceptionStatus {
		
	}
	
	public interface OnMessageCallback {
		void receiveMessage(IMUserMessage message);
		void sendMessageResult(IMUserMessage message, ExceptionStatus status);
	}
	
	private static IMMessageReceiver receiver = new IMMessageReceiver();

	private OnMessageCallback messageCallback;
	
	public void setMessageCallback(OnMessageCallback messageCallback) {
		this.messageCallback = messageCallback;
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		IMUserMessage message = (IMUserMessage) intent.getSerializableExtra("data");
		if (action.equals(getReceiveMessageAction())) {
			messageCallback.receiveMessage(message);
		} else if (action.equals(getSendMessageResultAction())) {
			messageCallback.sendMessageResult(message, null);
		}
	}

	/**
	 * 注册广播.
	 * @param context
	 * @param onInitCallback
	 */
	public static void onRegisterReceiver(Context context, OnMessageCallback messageCallback) {
		try {
			LocalBroadcastManager.getInstance(context).unregisterReceiver(receiver);
		} catch (Exception e) {
		}
		receiver.setMessageCallback(messageCallback);
		LocalBroadcastManager.getInstance(context).registerReceiver(receiver, receiver.getIntentFilter());
	}
	
	/**
	 * 取消注册广播.
	 * @param context
	 * @param onInitCallback
	 */
	public static void unRegisterReceiver(Context context) {
		LocalBroadcastManager.getInstance(context).unregisterReceiver(receiver);
	}
	
	/**
	 * 接收到信息广播.
	 * @param context
	 */
	public static void postReceiveMessageBroadcast(Context context, IMUserMessage message) {
		Intent intent = new Intent(getReceiveMessageAction());
		intent.putExtra("data", message);
		LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
	}
	
	/**
	 * 发送消息结果广播.
	 * @param context
	 */
	public static void postSendMessageResultBroadcast(Context context, IMUserMessage message) {
		Intent intent = new Intent(getSendMessageResultAction());
		intent.putExtra("data", message);
		LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
	}
	
	public static String getReceiveMessageAction() {
		return "com.imchezhil.im.receiver.receiveMessage";
	}
	
	public static String getSendMessageResultAction() {
		return "com.imchezhil.im.receiver.sendMessageResult";
	}
	
	private IntentFilter getIntentFilter() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(getReceiveMessageAction());
		filter.addAction(getSendMessageResultAction());
		return filter;
	}
}
